import { AfterViewInit, Component, OnDestroy, OnInit } from '@angular/core';
import { BaseFieldComponent } from '../base-field/base-field.component';
import * as dayjs from 'dayjs';
import { PermitConfig, PermitConfigId } from '../../../models';

@Component({
  selector: 'zepride-start-end-date',
  templateUrl: './start-end-date.component.html',
  styleUrls: ['./start-end-date.component.less', '../field.common.less']
})
export class StartEndDateComponent extends BaseFieldComponent implements OnInit, AfterViewInit, OnDestroy {

  data = [];
  isAuthprized = true;
  permitConfig: PermitConfig[] = [
    { mode: 'query', permitId: '查看', permitName: '', authObjectId: '' },
    { mode: 'edit', permitId: '编辑', permitName: '', authObjectId: '' }
  ];
  ngOnInit(): void {
    const bindData = this.bindData;
    if (bindData) {
      this.data = (bindData.split('~')).map((x: dayjs.ConfigType) => {
        return dayjs(x).toDate();
      });
    }
  }

  ngAfterViewInit() {
    setTimeout(() => {
      const authData = this.setAuthorityData();
      this.zeprideAuthorityData = {
        ...authData,
        afterChecked: this.afterAuthChecked.bind(this)
      };
    }, 0);
  }

  ngOnDestroy() {
    if (this.modelChange$) {
      this.modelChange$.unsubscribe();
    }
  }

  setBindData(value: Date[]) {
    const bindField = this.componentData.bindField;
    if (bindField) {
      this.dataModel[bindField] = value.map(x => {
        return dayjs(x).format('YYYY-MM-DD HH:mm:ss')
      }).join('~');
      this.engineService.dataModelChange$.next({
        bindField,
        value,
        identifyId: this.componentData.identifyId,
        tmpComItemId: this.tmpComItemId,
        dataModel: this.dataModel,
        selector: this.componentData.selector
      });
      this.componentData.defaultValue = value;
    } else {
      this.componentData.defaultValue = value;
    }
    // this.validate();
  }

  afterAuthChecked(params: {
    permitId: PermitConfigId;
    isAuthorized: boolean;
  }) {
    if (!params.isAuthorized && params.permitId === '编辑') {
      this.isAuthprized = false;
    }
  }

}
